package com.wangxu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangxu.blog.dao.dos.Archives;
import com.wangxu.blog.dao.mapper.ArticleBodyMapper;
import com.wangxu.blog.dao.mapper.ArticleMapper;
import com.wangxu.blog.dao.pojo.Article;
import com.wangxu.blog.dao.pojo.ArticleBody;
import com.wangxu.blog.service.*;
import com.wangxu.blog.vo.ArticleBodyVo;
import com.wangxu.blog.vo.ArticleVo;
import com.wangxu.blog.vo.Result;
import com.wangxu.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页查询的实现类
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public Result listArticle(PageParams pageParams) {
        /*
        1、分页查询article数据库表  参数一：当前页数 参数二：每页显示的数量
         */
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
        //Wrapper 查询条件编写
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //置顶排序并按照时间降序排序
        //相当于sql  order by create_date desc 降序
        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords(); //getRecords()获取记录
        List<ArticleVo> articleVoList = copyList(records,true,true);
        return Result.success(articleVoList);
    }

    @Override
    public Result HotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article :: getViewCounts);
        queryWrapper.select(Article:: getId,Article :: getTitle);
        queryWrapper.last("limit "+limit);
        //最终sql为: select id,title from article order by view_counts desc limit 4
        List<Article> articleList = articleMapper.selectList(queryWrapper); //根据wrapper条件查询所有记录
        return Result.success(copyList(articleList,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article :: getCreateDate); // 按照CreateDate值降序排序
        queryWrapper.select(Article :: getId,Article :: getTitle);  //设置查询的字段
        queryWrapper.last("limit " + limit);
        //最终sql为: select id,title from article order by createDate desc limit 3
        List<Article> articleList = articleMapper.selectList(queryWrapper); //根据wrapper条件查询所有数据
        return Result.success(copyList(articleList,false,false));
    }

    @Override
    public Result listArticles() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /*
        1、根据id查询 文章信息
        2、根据bodyId和categoryId 去做关联查询
         */
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true,true,true);
        //查看完文章了，新增阅读数
        //查看完文章之后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能就会比较低
        //更新增加了此次接口的 耗时 如果一旦更新出现问题，不能影响查询文章的操作
        //线程池 可以把更新操作 扔到线程池中去执行，和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));

        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    @Autowired
    private CategoryService categoryService;

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        //copy属性 把article中的属性复制到拥有相同属性中的articleVo里
        BeanUtils.copyProperties(article,articleVo);
        //把Article中的createDate属性赋值给articleVo类中的CreateDate属性
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口 都需要标签，作者信息
        //获取标签信息
        if (isTag){
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        //获取作者昵称
        if (isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        //获取body信息
        if (isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        //获取文章类别信息
        if (isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
